package sync

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

private var ticketNumber =10

private val mutex = Mutex()

/**
 * 不安全的买票
 * 线程不安全, 有负数的票
 */
fun main() = runBlocking {
    GlobalScope.launch { buyTicket("小铭") }
    GlobalScope.launch { buyTicket("志杰") }
    GlobalScope.launch { buyTicket("我") }

    println(readLine())
}

private suspend fun buyTicket(name: String) {
    mutex.withLock {
        while (ticketNumber > 0) {
            delay(50)
            println("$name 拿到第${ticketNumber--} 张票")
        }
    }
}